<template>
    <eui-page-frame topHeight="256" :bottomHeight="bottomHeight">
        <template #top>
            <view class="navigation">
                <eui-nav-bar :title="title" color="#000000" rightIcon="" />
                <eui-tab :tabs="tabData" :value="tabIndex" @change="tabChange">
                </eui-tab>
            </view>
        </template>
        <eui-page-content>
            <Summary v-if="tabIndex == 0"></Summary>
            <Items v-if="tabIndex == 1"></Items>
            <Points v-if="tabIndex == 2"></Points>
            <Results v-if="tabIndex == 3"></Results>
        </eui-page-content>
        <template #bottom>
            <view class="bt-button" v-if="bottomHeight > 0">
                <eui-button v-if="workData.c_status == '1'" type="primary" title="提交" @click="finished" />
                <eui-button v-if="workData.c_status == '5'" type="primary" title="复检完成" @click="recheck" />
            </view>
        </template>
    </eui-page-frame>
</template>

<script setup lang="ts">
import store from '@/store';
import { computed, provide, ref } from 'vue';
import Summary from './summary.vue';
import Items from './items.vue';
import Points from './points.vue';
import Results from './results.vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import useService from '@/hooks/useService';
import { getRelatedName, getOtherStorageName, getDictName } from '../components/RelatedName.js';
import type { patrolTaskg } from '../types/propertyTypes/property';
import dateRangUtil from '../../../common/dateRangUtil';

const { loginInfo } = store.state.value.main;

const service = useService({ prefix: "apiApi" });
const uniqueKey = '管易通物业模块服务';

const id = ref('');
const title = ref('日常运营巡场');
// const bottomHeight = ref(0);
const tabData = ref([{ name: '巡场概要' }, { name: '巡场项目' }, { name: '巡场范围' }, { name: '登记结果' }]);
const tabIndex = ref(0);

const summaryData = ref({});
const itemsData = ref({
    title: '巡检项目',
    itemClass: [],
    datas: [],
});
const pointsData = ref([]);
const workData = ref({});
const resultsData = ref<patrolTaskg[]>([]);

const mapEditStyle = (type: string) => {
    switch (type) {
        case "0":
            return 'radio';
        case "1":
            return 'multi';
        case "2":
            return 'text';
        case "3":
            return 'date';
        case "4":
            return 'number2';
        // case "5":
        // 	return 'textarea';
        // case "6":
        // 	return 'selector';
        default:
            return 'text';
    }
};

provide('patrolWorkbenchSummaryData', summaryData);
provide('patrolWorkbenchItemsData', itemsData);
provide('patrolWorkbenchPointsData', pointsData);
provide('patrolWorkbenchResultsData', resultsData);

const bottomHeight = computed(() => {
    if (workData.value.c_status == '1' || workData.value.c_status == '5') {
        return 124
    }
    else {
        return 0;
    }
}
)


onLoad((req) => {
    id.value = req?.id;
    title.value = decodeURIComponent(req?.project);
})

const tabChange = (e) => {
    tabIndex.value = e;
}

onShow(() => {
    getData();
})
/**获取数据 */
const getData = async () => {
    uni.showLoading({ title: "查询中...", mask: true });
    const res = await service.request(uniqueKey, 'GetPatrolTaskDetail', id.value);
    uni.hideLoading();
    if (res && res.ds && res.ds1 && res.ds2 && res.ds3 && res.ds4) {
        workData.value = res.ds[0];
        const summary = res.ds1[0];
        summaryData.value = {
            ...summary,
            c_adno: summary.c_adno ? '[' + summary.c_adno + ']' + getRelatedName('rdsDeparts', summary.c_adno) : '',
            c_change_userno: summary.c_change_userno ? '[' + summary.c_change_userno + ']' + getRelatedName('rdsUsers', summary.c_change_userno) : '',
            c_period: summary.c_plan_sdt.substring(11, 16) + '-' + summary.c_plan_edt.substring(11, 16),
            c_plan_scope: getDictName('巡检范围', summary.c_plan_scope)
        };
        itemsData.value.title = getOtherStorageName('巡检主题清单', summary.c_sub_id);
        itemsData.value.datas = res.ds3.map(t => {
            return {
                ...t,
                c_class_name: getDictName('巡检类型', t.c_class),
                c_options_show: t.c_options ? (JSON.parse(t.c_options).map(x => x.value + '、' + x.label).join('；') || t.c_note) : '',
                c_option_list: t.c_options ? JSON.parse(t.c_options).map(x => { return { text: x.label, value: x.value, checked: false } }) : []
                ,
                c_selected: res.ds5?.find(y => y.c_item_id == t.c_item_id)?.c_value || '',
                c_note: t.c_note ? t.c_note : '暂无说明',
                c_value: (res.ds5?.find(y => y.c_item_id == t.c_item_id)?.c_value || '') || (t.c_default_value || ''),
                c_input_type: mapEditStyle(t.c_edit_style),
            }
        });
        itemsData.value.itemClass = [...new Set(res.ds3.map(t => getDictName('巡检类型', t.c_class)))];

        console.log('workData', workData.value)

        pointsData.value = res.ds4.map(x => {
            const pointRes = res.ds5?.filter(y => y.c_point_id == x.c_point_id);
            console.log('pointRes', pointRes)
            const abnormalItems = pointRes?.filter(y => y.c_is_abnormal == '1');
            const rectifyItems = pointRes?.filter(y => y.c_is_abnormal == '1' && y.c_is_recheck != '1');
            console.log('abnormalItems', abnormalItems)
            return {
                ...x,
                c_option_list: x.c_option_list ? x.c_option_list.map(item => {
                    return {
                        ...item,
                        checked: pointRes?.find(r => r.c_item_id == t.c_item_id)?.c_value?.includes(item.value) ? true : false
                    }
                }) : [],
                status: pointRes?.length > 0 ? '已登记' : '未登记',
                statusColor: abnormalItems?.length > 0 ? (rectifyItems.length > 0 ? '#FF0000' : '#000000') : '#000000',
                abnormal: abnormalItems?.length > 0 ? (rectifyItems.length > 0 ? '有异常' : '已复检') : '无异常',
                c_work_status: workData.value.c_status,
            }
        });
        console.log('pointsData', pointsData.value)
        resultsData.value = res.ds5;
    }
    else {
        throw new Error('Invalid response data');
    }
}
/**确认完成 提交 */
const finished = async () => {
    if (pointsData.value.filter(x => x.status == '未登记').length > 0) {
        return uni.showToast({ title: '请先登记完成所有巡检点', icon: 'none' });
    }
    const isAbnormal = resultsData.value.filter(x => x.c_is_abnormal == '1').length > 0 ? '1' : '0';

    const saveModel = {
        isAbnormal,
        workData: {
            ...workData.value,
            c_status: isAbnormal == '1' ? '5' : '4', //isAbnormal=1则存在异常需要整改，状态5为待整改，状态4为已完成
            c_modify_userno: loginInfo.sUser,
            c_modify_dt: dateRangUtil.getCurrentDateTime(),
        },
    }
    uni.showLoading({ title: "提交中...", mask: true });
    const res = await service.request(uniqueKey, 'SavePatrolTaskData', saveModel);
    uni.hideLoading();
    if (res) {
        uni.showToast({ title: '提交成功', icon: 'none' });
        uni.navigateBack();
    }
}
/**复检完成 */
const recheck = async () => {
    if (pointsData.value.filter(x => x.abnormal == '有异常').length > 0) {
        return uni.showToast({ title: '请先复检完成有异常的巡检点', icon: 'none' });
    }
    const isAbnormal = '1';

    const saveModel = {
        isAbnormal,
        workData: {
            ...workData.value,
            c_status: '7', //isAbnormal=1则存在异常需要整改，状态5为待整改，状态4为已完成，状态7为复检完成
            c_modify_userno: loginInfo.sUser,
            c_modify_dt: dateRangUtil.getCurrentDateTime(),
        },
    }
    uni.showLoading({ title: "处理中...", mask: true });
    const res = await service.request(uniqueKey, 'SavePatrolTaskData', saveModel);
    uni.hideLoading();
    if (res) {
        uni.showToast({ title: '处理成功', icon: 'none' });
        uni.navigateBack();
    }
}


</script>

<style lang="scss" scoped>
.navigation {
    background: #FFFFFF;
    flex: 0 0 auto;
    margin-bottom: 0rpx;
}

.bt-button {
    background-color: white;
    padding: 20rpx;
    height: 80rpx;
    width: 96%;
    bottom: 20rpx;
    right: 0rpx;
    position: fixed;
    margin-bottom: -20rpx;
    display: flex;
    justify-content: space-between;
}
</style>